package com.next

import grails.gorm.transactions.Transactional
import org.springframework.security.access.annotation.Secured

import static org.springframework.http.HttpStatus.*

import grails.converters.JSON
import groovy.json.JsonOutput

@Secured(['ROLE_ADMINISTRATOR'])
@Transactional(readOnly = true)
class ContactController {

    static allowedMethods = [save: "POST", update: "PUT", delete: "DELETE"]

    def contactService

    def index(Integer max) {
        params.max = Math.min(max ?: 10, 100)
        respond Contact.list(params), model:[contactCount: Contact.count()]
    }

    def show(Contact contact) {
        respond contact
    }

    def create() {
        respond new Contact(params)
    }

    @Transactional
    def save(Contact contact) {
        if (contact == null) {
            transactionStatus.setRollbackOnly()
            notFound()
            return
        }

        if (contact.hasErrors()) {
            transactionStatus.setRollbackOnly()
            respond contact.errors, view:'create'
            return
        }

        contact.save flush:true

        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.created.message', args: [message(code: 'contact.label', default: 'Contact'), contact.id])
                redirect contact
            }
            '*' { respond contact, [status: CREATED] }
        }
    }

    def edit(Contact contact) {
        respond contact
    }

    @Transactional
    def update(Contact contact) {
        if (contact == null) {
            transactionStatus.setRollbackOnly()
            notFound()
            return
        }

        if (contact.hasErrors()) {
            transactionStatus.setRollbackOnly()
            respond contact.errors, view:'edit'
            return
        }

        contact.save flush:true

        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.updated.message', args: [message(code: 'contact.label', default: 'Contact'), contact.id])
                redirect contact
            }
            '*'{ respond contact, [status: OK] }
        }
    }

    @Transactional
    def delete(Contact contact) {

        if (contact == null) {
            transactionStatus.setRollbackOnly()
            notFound()
            return
        }

        contact.delete flush:true

        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.deleted.message', args: [message(code: 'contact.label', default: 'Contact'), contact.id])
                redirect action:"index", method:"GET"
            }
            '*'{ render status: NO_CONTENT }
        }
    }

    protected void notFound() {
        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.not.found.message', args: [message(code: 'contact.label', default: 'Contact'), params.id])
                redirect action: "index", method: "GET"
            }
            '*'{ render status: NOT_FOUND }
        }
    }

    @Secured(['permitAll'])
    def searchContact()
    {
        params.max = Math.min(params.max ? params.max.toInteger() : 10, 100)
        params.offset = params.offset ? params.offset.toInteger() : 0;

        def fullName = params["fullName"]
        String sql = "from Contact as u where 1=1"
        if (fullName)
        {
            sql += " and u.fullName like '%${fullName}%'"
        }

        sql += ' order by modifiedDate desc'

        println "sql:" + sql

        def max = params.max
        def offset = params.offset

        def list = Contact.findAll(sql, [max: max, offset: offset])
        def list1 = Contact.findAll(sql)
        def count = list1.size()

        respond list, model: [contactCount: count, params: params], view: 'index'
    }

    @Secured(['permitAll'])
    @Transactional
    def getOpenId()
    {
        def json = request.JSON
        println "************************* getOpenId ***************************"
        println json

        def code = json['code']
        def fullName = json['fullName']
        def avatarUrl = json['avatarUrl']

        if (!code)
        {
            def errors = [errorCode: 1000, errorMessage: "对不起，请先完成登录！"]
            render JsonOutput.toJson(errors), status: 400
            return
        }

        def openId = ""
        if (session.openId)
        {
            openId = session.openId
        }
        else
        {
            openId = contactService.getOpenId(code)
            session.openId = openId
        }

        println openId

        if (!openId)
        {
            def errors = [errorCode: 1001, errorMessage: "唯一标识获取失败，请稍后重试！"]
            render JsonOutput.toJson(errors), status: 400
            return
        }

        def contact = Contact.findByOpenId(openId)
        if (!contact) 
        {
            contact = new Contact()
            contact.openId = openId
            contact.fullName = fullName
            contact.avatarUrl = avatarUrl
            if (contact.validate())
            {
                contact.save flush: true    
            }
            else
            {
                println contact.errors
            }
        }
        
        def result = [openId: openId]
        render JsonOutput.toJson(result), status: 200
        return
    }

    @Secured('permitAll')
    @Transactional
    def getContactByOpenId()
    {
        def json = request.JSON
        println "************************* getContactByOpenId ***************************"
        println json

        def openId = json['id']
        if (!openId)
        {
            def errors = [errorCode: 3010, errorMessage: "请先完成登陆"]
            render JsonOutput.toJson(errors), status: 400
            return
        }

        render Contact.findByOpenId(openId) as JSON
        return
    }

    @Secured('permitAll')
    @Transactional
    def editContact()
    {
        def json = request.JSON
        println "************************* editContact ***************************"
        println json

        def openId = json['openId']
        if (!openId)
        {
            def errors = [errorCode: 3010, errorMessage: "请先完成登陆"]
            render JsonOutput.toJson(errors), status: 400
            return
        }

        def wechatNumber = json['wechatNumber']
        if (!wechatNumber)
        {
            def errors = [errorCode: 3010, errorMessage: "请输入微信号"]
            render JsonOutput.toJson(errors), status: 400
            return
        }

        def cellphone = json['cellphone']

        def contact = Contact.findByOpenId(openId)
        contact.wechatNumber = wechatNumber
        contact.cellphone = cellphone
        if (contact.validate()) 
        {
            contact.save flush: true
        }
        else
        {
            println contact.errors
        }

        render contact as JSON
        return
    }
}
